public class Solution394 {

    private int getMatchBracketInd(String s, int startInd){
        int leftBracketCount = 0;
        for (int i = startInd; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == '['){
                leftBracketCount++;
            }
            else if(c == ']'){
                leftBracketCount--;
                if(leftBracketCount == 0){
                    return i;
                }
            }
        }
        return -1;
    }

    public String decodeString(String s) {
        StringBuilder sb = new StringBuilder();
        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if('0' <= c && c <= '9'){
                num = num * 10 + c - '0';
            }
            else if(c == '['){
                int matchBracketInd = getMatchBracketInd(s, i);
                String subDecodeStr = decodeString(s.substring(i + 1, matchBracketInd));
                for (int j = 0; j < num; j++) {
                    sb.append(subDecodeStr);
                }
                i = matchBracketInd;
                num = 0;
            }
            else{
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Solution394 s = new Solution394();
        s.decodeString(
                "3[a]2[bc]");
    }
}
